/**
 * JungoPushModule
 * PushServiceImpl.java
 * 
 * Copyright 2013 Teachizen
 * Written by cloudstick
 *	2013. 8. 12. first written.
 *
 * note:
 */
package com.jungo.module.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import com.bnsworks.server.push.gcm.message.GcmMessage;
import com.bnsworks.server.push.gcm.result.GcmMulticastResult;
import com.bnsworks.server.push.gcm.sender.GcmSender;
import com.jungo.module.bean.Deal;
import com.jungo.module.bean.Job;
import com.jungo.module.dao.PushDao;

/**
 * @author cloudstick
 *
 */
@Service
@Slf4j
public class PushServiceImpl implements PushService {

	@Autowired
	private PushDao pushDao;
	
	/* (non-Javadoc)
	 * @see com.jungo.module.service.PushService#doPush(com.jungo.module.bean.Job)
	 */
	@Override
	public void doPush(List<Job> jobs) {
		
		GcmMessage message = new GcmMessage();
		message.setDelay_while_idle(true);
		message.setTime_to_live(60000);
		Map<String, String> map = new HashMap<String, String>();
		map.put("jungo", "noti");
		message.setData(map);
		List<String> ids = new ArrayList<String>();
		for ( Job job : jobs ) {
			log.info("Send message to user[{}]", job.getUserid());
			ids.add(job.getRid());
		}
		message.setRegistration_ids(ids);
		
		GcmSender sender = new GcmSender("AIzaSyDK7c2i73rRz8-Uz0o5sQmSWLmjRbCckJk");
		try {
			GcmMulticastResult result = sender.send(message, ids, 3);
			log.debug("Send result[{}]", result);
		} catch (IOException e) {
			log.error("Exception occured.", e);
		}
	}

	/* (non-Javadoc)
	 * @see com.jungo.module.service.PushService#getJob()
	 */
	@Override
	public List<Job> getJob() {
		
		List<Deal> deals = pushDao.getDeals();
		if ( deals == null || deals.isEmpty() ) {
			return null;
		}
		
		List<Job> jobs = new ArrayList<Job>();
		for ( Deal deal : deals ) {
			makeJob(deal, jobs);
			deal.setStatus(12);
			pushDao.updateDealStatus(deal);
		}
		
		return jobs;
	}
	
	private void makeJob(Deal deal, List<Job> jobs) {
		String userid = deal.getProduct_userid();
		String rid = pushDao.getRegistrationId(userid);
		if ( rid == null || "".equals(rid) ) {
			log.error("Have no registrationId with product user[{}]", userid);
			return;
		}
		jobs.add(makeJob(userid, rid, "message for registered product user."));
		
		userid = deal.getFavorite_userid();
		rid = pushDao.getRegistrationId(userid);
		if ( rid == null || "".equals(rid) ) {
			log.error("Have no registrationId with favorite user[{}]", userid);
			return;
		}
		jobs.add(makeJob(userid, rid, "message for registered favorite user."));
	}

	private Job makeJob(String userid, String rid, String message) {
		Job job = new Job();
		job.setUserid(userid);
		job.setRid(rid);
		job.setMessage(message);
		return job;
	}
}
